package org.rpc.proxy;

import org.rpc.blance.SimpleLoadBalance;
import org.rpc.common.Invocation;
import org.rpc.common.URL;
import org.rpc.protocol.HttpClient;
import org.rpc.register.RemoteRegister;

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class ProxyFactory {
    public static <T> T getProxy(Class<T> clazz) {
        Object proxyInstance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, (proxy, method, args) -> {
            Invocation invocation = new Invocation();
            invocation.setInterfaceName(clazz.getName());
            invocation.setMethodName(method.getName());
            invocation.setParameterTypes(method.getParameterTypes());
            invocation.setParameters(args);
            //获取注册中心服务
            List<URL> urls = RemoteRegister.get(clazz.getName());
            //实现负载均衡算法
            SimpleLoadBalance loadBalance = new SimpleLoadBalance();
            //创建客户端
            HttpClient client = new HttpClient();
            List<URL> hasBalanceUrls = new ArrayList<>();
            String result = null;
            int max = 3;
            while (max > 0) {
                urls.removeAll(hasBalanceUrls);
                URL url = loadBalance.loadBalance(urls);
                hasBalanceUrls.add(url);
                try {
                    result = client.send(url.getHostName(), url.getPort(), invocation);
                    max = 0;
                } catch (IOException e) {
                    max--;
                    //线程睡眠100毫秒
                    Thread.sleep(100);
                    e.printStackTrace();
                }
            }

            return result;
        });
        return (T) proxyInstance;
    }
}
